<template>
  <div>
    <div
      v-empty="!crm.customer.index"
      xs-empty-icon="nopermission"
      xs-empty-text="暂无权限"
      class="crm-container"
    >
      <!-- <c-r-m-table-head
        ref="crmTableHead"
        :crm-type="crmType"
        :sort-data="sortData"
        @filter="handleFilter"
        @handle="handleHandle"
        @scene="handleScene"
      /> -->
      <c-r-m-new-head
        ref="crmTableHead"
        :crm-type="crmType"
        :sort-data="sortData"
        :exportShow="true"
        @filter="handleFilter"
        @handle="handleHandle"
        @scene="handleScene"
        @on-export="exportInfos"
        @on-search="crmSearch"
        title="学员"
        placeholder="请输入学员名称/学员微信/电话"
        main-title="新建学员"
      >
      </c-r-m-new-head>
      <div class="table-container">
        <!-- 列表选择操作 -->
        <c-r-m-new-table-manage
          ref="crmTableManage"
          :crm-type="crmType"
          :sort-data="sortData"
          @handle="handleHandle"
        ></c-r-m-new-table-manage>
        <el-table
          v-loading="loading"
          id="crm-table"
          :row-height="40"
          :data="list"
          border
          :max-height="tableHeight"
          :cell-class-name="cellClassName"
          :row-key="`${crmType}Id`"
          class="n-table--border"
          highlight-current-row
          style="width: 100%"
          @row-click="handleRowClick"
          @sort-change="sortChange"
          @header-dragend="handleHeaderDragend"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            show-overflow-tooltip
            reserve-selection
            type="selection"
            align="center"
            width="55"
          />
          <!-- <el-table-column
            :resizable="false"
            prop="businessCheck"
            fixed
            label
            width="38"
          >
            <template slot="header">
              <i
                class="wk wk-business"
                style="cursor: not-allowed; color: #9da9c2"
              />
            </template>
            <template slot-scope="scope">
              <el-popover
                :disabled="scope.row.businessCount == 0"
                :offset="250"
                placement="right"
                popper-class="no-padding-popover"
                width="500"
                trigger="click"
              >
                <business-check
                  :data="scope"
                  :show="scope.row.show"
                  @click="relativeBusinessClick"
                  @close="businessClose($event, scope)"
                />
                <i
                  slot="reference"
                  :style="{ opacity: scope.row.businessCount > 0 ? 1 : 0 }"
                  class="wk wk-business"
                  style="color: #fc6e51"
                  @click="businessCheckClick($event, scope)"
                />
              </el-popover>
            </template>
          </el-table-column> -->
          <el-table-column
            v-for="(item, index) in fieldList"
            :key="index"
            :fixed="index == 0"
            :prop="item.prop"
            :label="item.label"
            :width="item.width"
            :sortable="item.prop != 'poolDay' ? 'custom' : false"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <template v-if="item.prop == 'dealStatus'">
                <i :class="scope.row[item.prop] | dealIcon" />
                <span>{{ scope.row[item.prop] | dealName }}</span>
              </template>
              <template v-else-if="item.prop == 'studentStatus'">
                <span>{{ scope.row[item.prop] | studentStatusName }}</span>
              </template>
              <template v-else-if="item.prop == 'status'">
                <i
                  v-if="scope.row.status == 2"
                  class="wk wk-circle-password customer-lock"
                />
              </template>
              <template v-else>{{
                fieldFormatter(scope.row, scope.column)
              }}</template>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            fixed="right"
            width="120"
            v-if="agreement && agreement.sign && agreement.sign.save"
          >
            <template slot-scope="scope">
              <el-button type="primary" @click="sign(scope.row)"
                >发起签署</el-button
              >
            </template>
          </el-table-column>
          <el-table-column label="关注" align="center" fixed="right" width="60">
            <template slot-scope="scope">
              <el-tooltip
                :content="scope.row.star == 0 ? '添加关注' : '取消关注'"
                effect="dark"
                placement="top"
              >
                <i
                  :class="{ active: scope.row.star != 0 }"
                  class="wk wk-focus-on focus-icon"
                  @click="toggleStar(scope.row)"
                />
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" fixed="right" width="40">
            <template slot="header">
              <field-set :crm-type="crmType" @change="setSave" />
            </template>
          </el-table-column>
          <!-- <wk-empty
          slot="empty"
          :props="{
            buttonTitle: '新建学员',
            showButton: saveAuth
          }"
          @click="createClick"
        /> -->
        </el-table>
        <div class="p-contianer">
          <el-pagination
            :current-page="currentPage"
            :page-sizes="pageSizes"
            :page-size.sync="pageSize"
            :total="total"
            :pager-count="5"
            class="p-bar"
            background
            layout="prev, pager, next, sizes, total, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
    <!-- 相关详情页面 -->
    <c-r-m-all-detail
      :visible.sync="showDview"
      :crm-type="rowType"
      :id="rowID"
      class="d-view"
      @handle="handleHandle"
      @sign="signHandle"
    />

    <!-- 新建 -->
    <c-r-m-all-create
      v-if="createShow"
      :crm-type="createType"
      :action="createAction"
      @close="createShow = false"
      @save-success="saveSuccess"
    />

    <sign-create
      v-if="isCreate"
      :show="isCreate"
      :action="createActionInfo"
      @save-success="signhandleHandle"
      @close="hideView"
    ></sign-create>

    <el-dialog
      :visible="signDialogShow"
      title="发起签署"
      width="590px"
      :before-close="() => (signDialogShow = false)"
      :close-on-click-modal="false"
    >
      <div class="color-02">
        该学员已发起电子协议
        <span style="color:#FF3F3F;">{{ signNum }}份</span>
        ，是否确定要重复发起？可点击详情页面，查看签署记录！
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="signDialogShow = false">取 消</el-button>
        <el-button type="primary" @click="signOpen">确定发起</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import CRMAllCreate from "../components/CRMAllCreate";
import { mapGetters } from "vuex";
import CRMAllDetail from "@/views/crm/components/CRMAllDetail";
import BusinessCheck from "./components/BusinessCheck"; // 相关商机
import { getContractNum, canSubmit } from "@/api/admin/agreement";
import TableMixin from "../mixins/Table";

import signCreate from "./signCreate";
export default {
  /** 学员管理 的 学员列表 */
  name: "CustomerIndex",
  components: {
    CRMAllDetail,
    BusinessCheck,
    CRMAllCreate,
    signCreate
  },
  filters: {
    dealIcon(statu) {
      return statu == 1 ? "wk wk-success deal-suc" : "wk wk-close deal-un";
    },

    dealName(statu) {
      return statu == 1 ? "已成交" : "未成交";
    },
    studentStatusName(statu) {
      return statu === 0 ? "已退学" : statu == 1 ? "已入学" : "--";
    }
  },
  mixins: [TableMixin],
  data() {
    return {
      crmType: "customer",
      createType: "customer",
      createAction: {
        type: "save",
        id: "",
        data: {}
      },
      createShow: false,
      isShow: true,
      isCreate: false, // 创建
      createActionInfo: { type: "save", data: null },
      headIndex: 0,
      details: {}, // 详情
      signDialogShow: false, // 签署提示
      signNum: "" // 协议份数
    };
  },
  computed: {
    ...mapGetters(["CRMConfig"]),
    menuItems() {
      const temp = [];
      if (this.crm && this.crm.customer) {
        temp.push({
          title: "学员",
          path: "customer",
          icon: require("@/assets/img/crm/customer.png")
        });
      }

      if (this.crm && this.crm.pool) {
        temp.push({
          title: "公海",
          path: "seas",
          icon: require("@/assets/img/crm/seas_not.png")
        });
      }

      if (this.crm && this.crm.customer && this.crm.customer.nearbyCustomer) {
        temp.push({
          title: "附近学员",
          path: "nearby",
          icon: require("@/assets/img/crm/nearby_not.png")
        });
      }

      return temp;
    }
  },
  mounted() {},
  activated() {
    if (this.isRequested) {
      this.getList();
    }
  },
  deactivated() {
    // this.$refs.elMenu.activeIndex = this.crmType;
  },
  methods: {
    /**
     * 左侧菜单选择
     */
    menuSelect(key, keyPath) {
      this.$emit("menu-select", key, keyPath);
    },

    relativeBusinessClick(data) {
      this.rowID = data.businessId;
      this.rowType = "business";
      this.showDview = true;
    },

    /**
     * 通过回调控制class
     */
    cellClassName({ row, column, rowIndex, columnIndex }) {
      if (column.property === "customerName") {
        return "can-visit--underline";
      } else if (column.property === "businessCheck") {
        return "can-visit";
      } else {
        return this.statusClass(row, column, rowIndex, columnIndex);
      }
    },
    // 商机信息查看
    businessCheckClick(e, scope) {
      if (scope.row.businessCount == 0) {
        return;
      }

      const popoverEl = e.target.parentNode;
      this.$set(scope.row, "show", !scope.row.show);
      popoverEl.__vue__.showPopper = !scope.row.show;
    },
    businessClose(e, scope) {
      const popoverEl = e.parentNode;
      popoverEl.__vue__.showPopper = false;
      this.$set(scope.row, "show", false);
    },

    /**
     * 新建点击
     */
    createClick() {
      this.createType = this.crmType;
      this.createAction = {
        type: "save",
        id: "",
        data: {}
      };
      this.createShow = true;
    },

    hideView() {
      this.isCreate = false;
    },

    signHandle(data) {
      this.sign(data);
    },

    signhandleHandle(data) {
      this.isCreate = false;
      this.getList();
    },

    /**
     * 创建成功
     */
    saveSuccess(data) {
      if (data.type == "customer") {
        this.handleHandle(data);
        if (data.createContacts) {
          this.createType = "contacts";
          this.createAction = {
            type: "relative",
            crmType: "customer",
            data: {
              customer: data.data
            }
          };
          this.createShow = true;
        }
      }
    },
    // 发起签署
    async sign(data) {
      const result = await canSubmit();
      if (result && result.result) {
        this.$message.error("协议份数余额不足，请联系管理员充值");
        return;
      }
      this.details = data;
      const res = await getContractNum({
        customerId: data.customerId,
        customerType: "学员"
      });
      if (res && res.code === 0) {
        this.signNum = res.data.num;
        res.data.num > 0 ? (this.signDialogShow = true) : this.signOpen();
      }
    },

    // 确认签署
    signOpen() {
      this.signDialogShow = false;
      this.isCreate = true;
      this.createActionInfo.data = this.details;
    }
  }
};
</script>

<style lang="scss" scoped>
@import "../styles/table.scss";
// /deep/.right-container .xr-btn--orange {
//   display: none;
// }
</style>
